﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Collections;

namespace OrangePrj
{
    public partial class FormAdministration : Form
    {
        private String text1, text2, text3, path;
        private int index, bytesRead, adminCount;
        private List<ListViewItem> userList;
        private StreamReader reader;
        private StreamWriter writer;
        private Stream input;        
        private FileInfo inputFile;
        private byte[] buffer;
        private bool nameSortPress, adminSortPress;

        const int bufSize = 1024;

        public FormAdministration(User user)
        {
            if (!user.IsAdmin)
            {
                MessageBox.Show("У вас нет прав администратора");
                //Close();
            }
            InitializeComponent();
            userList = new List<ListViewItem>();
            index = 0;
            adminCount = 0;
            labelAdministratorName.Text = user.Name;
            nameSortPress = false;
            adminSortPress = false;

            try
            {
                path = Directory.GetCurrentDirectory();
                //Расшифровка
                
                input = File.OpenRead(path + @"\Users");
                Stream output = File.OpenWrite(path + @"\Test1");

                buffer = new byte[bufSize];
                while ((bytesRead = input.Read(buffer, 0, bufSize)) > 0)
                {
                    for (int i = 0; i < bufSize; i++)
                        buffer[i] -= 20;

                    output.Write(buffer, 0, bytesRead);
                }
                input.Close();
                output.Close();

                inputFile = new FileInfo(path + @"\Test1");
                reader = inputFile.OpenText();

                while ((text1 = reader.ReadLine()) != null &&
                    (text2 = reader.ReadLine()) != null &&
                    (text3 = reader.ReadLine()) != null)
                {
                    ListViewItem temp = listViewUsers.Items.Add(text1);
                    if (text3 == "1")
                        temp.SubItems.Add("Администратор");
                    else
                        temp.SubItems.Add("Студент");
                    temp.SubItems.Add(text2);

                    userList.Add(temp);
                    index++;
                }

                
                reader.Close();
                inputFile.Delete();
                
                            
            } catch(FileNotFoundException)
            {
                labelAdministratorName.Text = "Файл не существует!";
            } catch(Exception ex)
            {
                MessageBox.Show("Ошибка: " + ex.Message);
            }

            for (int i = 0; i < userList.Count; i++)
            {
                if (userList[i].SubItems[1].Text == "Администратор")
                {
                    adminCount++;
                }
            }
        }

        private void buttonLoadUser_Click(object sender, EventArgs e)
        {
            
            if(listViewUsers.SelectedItems.Count > 0)
            {
                warningLabel.Visible = false;
                
                textBoxUserName.Text = listViewUsers.SelectedItems[0].Text;
                textBoxPassword.Text = listViewUsers.SelectedItems[0].SubItems[2].Text;
                comboBoxPermissions.Text = listViewUsers.SelectedItems[0].SubItems[1].Text;

                if (listViewUsers.SelectedItems[0].SubItems[1].Text == "Администратор")
                {
                    adminCount--;
                    if (adminCount < 1)
                    {
                        warningLabel.Text = "Необходимо чтобы был хотя бы один администратор";
                        buttonOK.Enabled = false;
                        warningLabel.Visible = true;
                    }
                }
                userList.RemoveAt(listViewUsers.SelectedItems[0].Index);
                listViewUsers.SelectedItems[0].Remove();

                index--;

                textBoxUserName.Focus();
                textBoxUserName.SelectAll();
                
                
            }
            else
            {
                warningLabel.Text = "Выберите пользователя из списка";
                warningLabel.Visible = true;
            }

        }

        private void buttonSaveUser_Click(object sender, EventArgs e)
        {
            bool flag = true;
            if (textBoxUserName.Text == "" || textBoxPassword.Text == "" || comboBoxPermissions.Text == "")
            {
                warningLabel.Text = "Все поля для ввода должны быть заполнены!";
                warningLabel.Visible = true;
            } 
            else
            {
                for(int i = 0; i < index; i++)
                {
                    if (textBoxUserName.Text.ToLower() == listViewUsers.Items[i].Text.ToLower())
                    {
                        warningLabel.Text = "Пользователь с таким именем уже существует в списке";
                        warningLabel.Visible = true;
                        flag = false;
                        break;
                    }
                    else
                        flag = true;
                }
                if (flag)
                {
                    ListViewItem temp = listViewUsers.Items.Add(textBoxUserName.Text);
                    temp.SubItems.Add(comboBoxPermissions.Text);
                    temp.SubItems.Add(textBoxPassword.Text);
                    
                    userList.Add(temp);

                    if (comboBoxPermissions.Text == "Администратор")
                    {
                        buttonOK.Enabled = true;
                        warningLabel.Visible = false;
                        adminCount++;
                    }
                    textBoxUserName.Text = "";
                    textBoxPassword.Text = "";
                    comboBoxPermissions.Text = "";
                    warningLabel.Visible = false;
                    index++;
                }
            }

        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            writer = new StreamWriter(path + @"\Test1", false);
            for (int i = 0; i < userList.Count; i++)
            {
                writer.WriteLine(userList[i].Text);
                writer.WriteLine(userList[i].SubItems[2].Text);
                if (userList[i].SubItems[1].Text == "Студент")
                    writer.WriteLine("0");
                else
                    writer.WriteLine("1");
            }

            writer.Close();

            //Шифрование

            FileSystemInfo temp1 = new FileInfo(path + @"\Users");
            temp1.Delete();
            input = File.OpenRead(path + @"\Test1");
            Stream outputStream = File.OpenWrite(path + @"\Users");

            while ((bytesRead = input.Read(buffer, 0, bufSize)) > 0)
            {
                for (int i = 0; i < bufSize; i++)
                    buffer[i] += 20;

                outputStream.Write(buffer, 0, bytesRead);
            }
            input.Close();
            outputStream.Close();
            FileSystemInfo temp = new FileInfo(path + @"\Test1");
            temp.Delete();
        }

        private void checkBoxShowPassword_CheckedChanged(object sender, EventArgs e)
        {
            if (textBoxPassword.UseSystemPasswordChar == true)
            {
                textBoxPassword.UseSystemPasswordChar = false;
            } else
            {
                textBoxPassword.UseSystemPasswordChar = true;
            }
        }

        private void listViewUsers_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            UserCompare uc;
            if (e.Column == 0)
            {

                if (nameSortPress)
                {
                    uc = new UserCompare(UserCompareType.administration);
                    nameSortPress = false;
                }
                else
                {
                    uc = new UserCompare(UserCompareType.name);
                    nameSortPress = true;
                }
                userList.Sort(uc);
                for (int i = 0; i < index; i++)
                    listViewUsers.Items[0].Remove();
                foreach (ListViewItem item in userList)
                {
                    listViewUsers.Items.Add(item);
                }
            }
            else if (e.Column == 1)
            {
                if (adminSortPress)
                {
                    uc = new UserCompare(UserCompareType.administrationBack);
                    adminSortPress = false;
                }
                else
                {
                    uc = new UserCompare(UserCompareType.administration);
                    adminSortPress = true;
                }
                userList.Sort(uc);
                for (int i = 0; i < index; i++)
                    listViewUsers.Items[0].Remove();
                foreach (ListViewItem item in userList)
                {
                    listViewUsers.Items.Add(item);
                }
            }
        }


    }
    public class UserCompare : IComparer<ListViewItem>
    {
        public UserCompareType compareType;

        public UserCompare(UserCompareType compareType)
        {
            this.compareType = compareType;
        }

        public int Compare(ListViewItem x, ListViewItem y)
        {
            switch (compareType)
            {
                case UserCompareType.name:
                    return x.Text.CompareTo(y.Text);
                case UserCompareType.nameBack:
                    return y.Text.CompareTo(x.Text);
                case UserCompareType.administration:
                    return x.SubItems[1].Text.CompareTo(y.SubItems[1].Text);
                case UserCompareType.administrationBack:
                    return y.SubItems[1].Text.CompareTo(x.SubItems[1].Text);
                default:
                    throw new ArgumentException("Недопустимый тип для сравнения");
            }

        }
    }
}


